//
//  LoginViewController.swift
//  SwiftDemo
//
//  Created by cqf on 2025/10/11.
//

import UIKit

class LoginViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        setupModelUI()
//        setupUI()
//        setupConstraints()
    }
    
    private let usernameField = UITextField()
    private let passwordField = UITextField()
    private let loginButton   = UIButton(type: .system)
    private let messageLabel  = UILabel()
    
    func setupModelUI() {
        let pwdField = IconTextField(
            placeholder: "请输入密码",
            icon: UIImage(systemName: "lock"),
            buttonTitle: "显示"
        )
        pwdField.textField.isSecureTextEntry = true
        pwdField.iconTintColor = .systemBlue

        // 点击右边按钮切换密码可见性
        pwdField.rightButton.addAction(UIAction { [weak pwdField] _ in
            pwdField?.textField.isSecureTextEntry.toggle()
            let title = (pwdField?.textField.isSecureTextEntry ?? false) ? "显示" : "隐藏"
            pwdField?.rightButton.setTitle(title, for: .normal)
        }, for: .touchUpInside)
        
        view.addSubview(pwdField)
        // 布局示例
        pwdField.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            pwdField.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            pwdField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32),
            pwdField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32),
            pwdField.heightAnchor.constraint(equalToConstant: 48)
        ])
    }
    
    func setupUI() {
        // 用户名
        usernameField.placeholder = "用户名"
        usernameField.borderStyle = .roundedRect
        usernameField.autocapitalizationType = .none

       // 密码
        passwordField.placeholder = "密码"
        passwordField.borderStyle = .roundedRect
        passwordField.isSecureTextEntry = true

       // 登录按钮
        loginButton.setTitle("登录", for: .normal)
        loginButton.titleLabel?.font = .boldSystemFont(ofSize: 18)
        loginButton.addTarget(self, action: #selector(loginTapped), for: .touchUpInside)

       // 提示文字
        messageLabel.textColor = .systemRed
        messageLabel.textAlignment = .center
        messageLabel.numberOfLines = 0
        
        // 加入视图
        [usernameField, passwordField, loginButton, messageLabel].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
        }
    }
    
    func setupConstraints() {
        NSLayoutConstraint.activate([
        usernameField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
        usernameField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40),
        usernameField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40),

        passwordField.topAnchor.constraint(equalTo: usernameField.bottomAnchor, constant: 20),
        passwordField.leadingAnchor.constraint(equalTo: usernameField.leadingAnchor),
        passwordField.trailingAnchor.constraint(equalTo: usernameField.trailingAnchor),

        loginButton.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 30),
        loginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        loginButton.widthAnchor.constraint(equalToConstant: 120),
        loginButton.heightAnchor.constraint(equalToConstant: 44),

        messageLabel.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 20),
        messageLabel.leadingAnchor.constraint(equalTo: usernameField.leadingAnchor),
        messageLabel.trailingAnchor.constraint(equalTo: usernameField.trailingAnchor)
        ])
    }
    
    // MARK: - 按钮事件
    @objc private func loginTapped() {
        // 简单校验
        guard let user = usernameField.text, !user.isEmpty else {
            showMessage("用户名不能为空")
            return
        }
        guard let pwd = passwordField.text, !pwd.isEmpty else {
            showMessage("密码不能为空")
            return
        }
        guard pwd.count >= 6 else {
            showMessage("密码至少 6 位")
            return
        }

        // 成功
        showMessage("") // 清空错误
        let alert = UIAlertController(title: "提示", message: "登录成功", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }

    private func showMessage(_ text: String) {
        messageLabel.text = text
        
        //
        var names = ["test","test1","test2"];
        for name in names {
            print(name)
        }
        //
        let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
        for (animalName, legCount) in numberOfLegs {
            print("\(animalName)s have \(legCount) legs")
        }
    }
    
    
    class IconTextField: UIView {
        let textField = UITextField()
        let rightButton = UIButton(type: .system)
        
        var iconTintColor: UIColor = .systemGray {
            didSet { iconView.tintColor = iconTintColor }
        }
        private let iconView = UIImageView()
        private let backgroundLayer = CALayer()
        
        // MARK: - 初始化
        convenience init(placeholder: String = "",
                         icon: UIImage? = nil,
                         buttonTitle: String? = nil,
                         buttonImage: UIImage? = nil) {
            self.init(frame: .zero)
            iconView.image = icon
            rightButton.setTitle(buttonTitle, for: .normal)
            rightButton.setImage(buttonImage, for: .normal)
            textField.placeholder = placeholder
            setup()
            layout()
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setup()
            layout()
        }
        // MARK: - 绘制圆角背景
        override func layoutSubviews() {
            super.layoutSubviews()
            // 底部白色圆角层
            backgroundLayer.frame = bounds
            backgroundLayer.backgroundColor = UIColor.white.cgColor
            backgroundLayer.cornerRadius = 8
            backgroundLayer.shadowColor = UIColor.black.withAlphaComponent(0.08).cgColor
            backgroundLayer.shadowOffset = CGSize(width: 0, height: 2)
            backgroundLayer.shadowOpacity = 1
            backgroundLayer.shadowRadius = 4
        }
        
        private func setup() {
            // 基本外观
            iconView.contentMode = .scaleAspectFit
            iconView.tintColor = iconTintColor
            
            textField.borderStyle = .none
            textField.font = .systemFont(ofSize: 16)
            textField.textColor = .label
            
            // 把圆角背景插到最底层
            layer.insertSublayer(backgroundLayer, at: 0)
            
            // 拼装
            [iconView, textField, rightButton].forEach {
                $0.translatesAutoresizingMaskIntoConstraints = false
                addSubview($0)
            }
        }
        private func layout() {
            let margin: CGFloat = 12
            let iconSize: CGFloat = 20
            let buttonWidth: CGFloat = 60
            
            NSLayoutConstraint.activate([
                // 图标居中左侧
                iconView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
                iconView.centerYAnchor.constraint(equalTo: centerYAnchor),
                iconView.widthAnchor.constraint(equalToConstant: iconSize),
                iconView.heightAnchor.constraint(equalToConstant: iconSize),
                
                // 右边按钮
                rightButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
                rightButton.centerYAnchor.constraint(equalTo: centerYAnchor),
                rightButton.widthAnchor.constraint(equalToConstant: buttonWidth),
                
                // 输入框夹在中间
                textField.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: margin),
                textField.trailingAnchor.constraint(equalTo: rightButton.leadingAnchor, constant: -margin),
                textField.topAnchor.constraint(equalTo: topAnchor, constant: margin),
                textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin)
            ])
        }
    }
}
